import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;

public class ManageCartServlet extends HttpServlet
{

	public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException
	{

		String newitem = req.getParameter("book");
		String action = req.getParameter("action");
		Hashtable ht = new Hashtable();
		HttpSession session = req.getSession(true);
		if (session.getAttribute("cart") != null)
		{
			ht = (Hashtable)session.getAttribute("cart");
			if ("Add".equals(action))
			{
				if (ht.containsKey(newitem))
				{
					int value = 1;
					if (ht.containsKey(newitem))
					{
						Integer currentQuantity = (Integer)ht.get(newitem);
						value += currentQuantity.intValue();
					}
					ht.put(newitem, new Integer(value));
					session.setAttribute("cart", ht);
					String cartXml = toXml(ht);
					res.setContentType("text/xml");
					res.getWriter().write(cartXml);
				}
				else
				{
					ht.put(newitem, 1);
					session.setAttribute("cart", ht);
					String cartXml = toXml(ht);
					res.setContentType("text/xml");
					res.getWriter().write(cartXml);
				}
			}
			else
			{
				ht.remove(newitem);
				session.setAttribute("cart", null);
				String cartXml = toXml(ht);
				res.setContentType("text/xml");
				res.getWriter().write(cartXml); ;
			}
		}
		else
		{
			ht.put(newitem, 1);
			session.setAttribute("cart", ht);
			String cartXml = toXml(ht);
			res.setContentType("text/xml");
			res.getWriter().write(cartXml);
		}
	}

	public String toXml(Hashtable ht)
	{
		StringBuffer xmlDoc = new StringBuffer();
		xmlDoc.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
		xmlDoc.append("<cart>\n");

		for (Iterator<String> x = ht.keySet().iterator(); x.hasNext(); )
		{
			String item = x.next();
			int Quantity = ((Integer)ht.get(item)).intValue();
			xmlDoc.append("<book>\n");
			xmlDoc.append("<title>");
			xmlDoc.append(item);
			xmlDoc.append("</title>\n");
			xmlDoc.append("<quantity>");
			xmlDoc.append(Quantity);
			xmlDoc.append("</quantity>\n");
			xmlDoc.append("</book>\n");
		}
		xmlDoc.append("</cart>\n");
		return xmlDoc.toString();

	}
}
